//
//  IFly.m
//  NoteBook
//
//  Created by 云荒 on 15/11/20.
//  Copyright © 2015年 北落师门. All rights reserved.
//

#import "IFly.h"

@implementation IFly

static IFly *manager = nil;

+(instancetype)shareManager
{
    static dispatch_once_t once;
    dispatch_once(&once, ^{
        if (manager == nil) {
            manager = [[self alloc]init];
            
        }
    });
    return manager;
}

-(void)recognizerBlock:(void (^)(NSString *))rec
{
    self.onResult = rec;
    
    iFlySpeechRecognizer = [IFlySpeechRecognizer sharedInstance];
    
    iFlySpeechRecognizer.delegate = self;
    
    [iFlySpeechRecognizer setParameter:@"565453bc" forKey:@"appid"];
    
    [iFlySpeechRecognizer setParameter:@"iat" forKey:@"domain"];
    
    [iFlySpeechRecognizer setParameter:@"1800" forKey:@"vad_eos"];
    
    [iFlySpeechRecognizer setParameter:@"8000" forKey:@"sample_rate"];
    
    [iFlySpeechRecognizer startListening];
}


-(void)onError:(IFlySpeechError *)errorCode
{
    NSLog(@"%@",errorCode);
}

-(void)onResults:(NSArray *)results isLast:(BOOL)isLast
{
    NSMutableString *result = [[NSMutableString alloc]init];
    NSDictionary *dic = [results firstObject];
    
    for (NSString *key in dic) {
        [result appendFormat:@"%@",key];
    }
    NSString *resultStr = [self stringFromJson:result];
    self.onResult(resultStr);
        NSLog(@"%@",result);
}

-(void)stopReconizer
{
    [iFlySpeechRecognizer stopListening];
    [self.Stopdelegate stopButton];
}

-(void)onBeginOfSpeech
{
    
}

-(void)onEndOfSpeech
{
    [self.Stopdelegate stopButton];
}

-(void)onCancel
{
    
}


-(NSString *)stringFromJson:(NSString*)params
{
    if (params == NULL) {
        return nil;
    }
    
    NSMutableString *tempStr = [[NSMutableString alloc] init];
    NSDictionary *resultDic  = [NSJSONSerialization JSONObjectWithData:    //返回的格式必须为utf8的,否则发生未知错误
                                [params dataUsingEncoding:NSUTF8StringEncoding] options:kNilOptions error:nil];
    
    if (resultDic!= nil) {
        NSArray *wordArray = [resultDic objectForKey:@"ws"];
        
        for (int i = 0; i < [wordArray count]; i++) {
            NSDictionary *wsDic = [wordArray objectAtIndex: i];
            NSArray *cwArray = [wsDic objectForKey:@"cw"];
            
            for (int j = 0; j < [cwArray count]; j++) {
                NSDictionary *wDic = [cwArray objectAtIndex:j];
                NSString *str = [wDic objectForKey:@"w"];
                [tempStr appendString: str];
            }
        }
    }
    return tempStr;
}




@end
